package bbcache

import (
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis"
	"github.com/shopspring/decimal"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/imsdk"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/messages/sports"
	"sync"
)

type (
	Odds struct {
		CompanyId        int             `json:"company_id"`        // 指数公司id，详见状态码->指数公司ID
		ExponentialType  string          `json:"exponential_type"`  // 指数类型：asia-亚盘、eu-欧赔、bs-大小球、cr-角球
		ExponentialScore string          `json:"exponential_score"` // 进球比分 or 角球比(cr)，主队-客队
		MatchId          int             `json:"match_id"`          // 比赛id
		MatchStatus      int             `json:"match_status"`      // 比赛状态，详见状态码->比赛状态 - int
		OddsStatus       int             `json:"odds_status"`       // 是否封盘：1-封盘,0-未封盘
		Odds1            decimal.Decimal `json:"odds_1"`            // 主胜/大球/
		Odds2            decimal.Decimal `json:"odds_2"`            // 和局/盘口
		Odds3            decimal.Decimal `json:"odds_3"`            // 客胜/小球
		ChangeTime       int64           `json:"change_time"`       // 变化时间
		CompetitionTime  string          `json:"competition_time"`  // 比赛进行时间
	}

	OddsCache struct {
		rds redis.UniversalClient
	}
)

var oddsInstance *OddsCache
var oddsOnce sync.Once

func NewOddsCache() *OddsCache {
	oddsOnce.Do(func() {
		oddsInstance = &OddsCache{
			rds: global.GetRds(),
		}
	})
	return oddsInstance
}

// 生成篮球指数key
func (o *OddsCache) genOddsKey(matchId int) string {
	return fmt.Sprintf("match_live:basketball_odds:%d", matchId)
}

// SetOddsCache 设置缓存
// 每次都是覆盖，这里只存最新的指数
func (o *OddsCache) SetOddsCache(records []Odds) {
	recordMap := make(map[int][]Odds)
	for _, record := range records {
		recordMap[record.MatchId] = append(recordMap[record.MatchId], record)
	}
	pp := o.rds.Pipeline()
	for matchId, item := range recordMap {
		message := sports.OddsResponseMessage{
			SentMessageStruct: messages2.SentMessageStruct{Type: messages2.OddsMessageType},
			OddsJson:          item,
		}
		bytes, _ := json.Marshal(message)
		err := pp.Set(o.genOddsKey(matchId), string(bytes), CacheExpire).Err()
		if err != nil {
			global.Log.Errorf("set cache error: %v", err)
			continue
		}
		imsdk.GetSdk().BroadcastInterface(matchId, message, 0)
	}

	_, err := pp.Exec()
	if err != nil {
		global.Log.Errorf("Pipeline run error: %v", err)
	}

}

// GetOddsCache 获取缓存
func (o *OddsCache) GetOddsCache(matchId int) string {
	result, err := o.rds.Get(o.genOddsKey(matchId)).Result()
	if err != nil {
		return ""
	}
	return result
}
